package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.TimeUtils
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.model.bean.MemberReservationResponse
import com.gexiaobao.pigeon.app.model.param.AddMemberReservationParam
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.ActivityReservedMembershipBinding
import com.gexiaobao.pigeon.ui.activity.ActivityAddress
import com.gexiaobao.pigeon.ui.adapter.ProofPictureAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogModifyAppointmentInfo
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.finish
import me.hgj.jetpackmvvm.util.startActivityForResult
import java.text.SimpleDateFormat


/**
 * @Author      : hxw
 * @Date        : 2024/5/21 17:19
 * @Describe    : 预约会员通道
 */
class ActivityMakeAnAppointment : BaseActivity<OrgDetailViewModel, ActivityReservedMembershipBinding>() {

    private var areaId: Int = 0
    private var cityId: Int = 0
    private var provinceId: Int = 0
    private var mIdCardState = false
    private var mState = 0
    private var mId = 0
    private var mRaceId = 0

    private lateinit var memberInfo: MemberReservationResponse
    private val mAdapter: ProofPictureAdapter by lazy { ProofPictureAdapter(arrayListOf()) }
    private var dataImageList: MutableList<String> = arrayListOf()

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.viewmodel = mViewModel
        val memberName = intent.getStringExtra("memberName")
        val raceName = intent.getStringExtra("raceName")
        val orgIcon = intent.getStringExtra("orgIcon")
        mDatabind.includeOrgTitle.tvIncludeOrgName.text = memberName
        mDatabind.includeOrgTitle.tvIncludeOrgRaceName.text = raceName
        ImageLoaderManager.loadCircleImageFall(this, orgIcon, mDatabind.includeOrgTitle.ivOrgIcon, R.mipmap.profilepic_str_1)

        mRaceId = intent.getIntExtra("raceId", 0)
        mViewModel.getMemberReservation(mRaceId.toString())

        mDatabind.recyclerViewPicProof.layoutManager = GridLayoutManager(this, 3)
        mDatabind.recyclerViewPicProof.adapter = mAdapter

        mAdapter.setOnItemClickListener { _, _, position ->
            openAdapterBigImage(position, mDatabind.recyclerViewPicProof, dataImageList)
        }

//        mDatabind.rootView.setAnchor(findViewById(R.id.llRealNameInfo))
//        mDatabind.rootView.setPopupListener { isPop ->
//
//        }
//        mDatabind.rootView.setMarginKeyboard(100)

    }

    private fun finishActivityAppointment() {
        val intent = Intent()
        intent.putExtra("isRefresh", true)
        finish(intent)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 新增会员预定 */
        mViewModel.addMemberResult.observe(this) {
            if (it.isSuccess) {
                finishActivityAppointment()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取会员预定详情 */
        mViewModel.memberReservationResult.observe(this) {
            if (it != null) {
                refreshUi(it)
            }
        }
    }

    @SuppressLint("SimpleDateFormat", "NotifyDataSetChanged")
    private fun refreshUi(it: MemberReservationResponse) {
        memberInfo = it
        mDatabind.data = it
        mIdCardState = it.idCardState
        mState = it.state//1-审核中 2-审核通过 3-审核失败
        mDatabind.tvSubmitAppointmentProof.isVisible = mState == 1 && it.voucherState
        mDatabind.llVoucherPicture.isVisible = mState == 1 && it.voucherState
        dataImageList.clear()
        dataImageList.addAll(it.voucher)

        provinceId = it.province
        cityId = it.city
        areaId = it.region
        mId = it.id

        val format = SimpleDateFormat("yyyy-MM-dd")
        val startTime = TimeUtils.millis2String(TimeUtils.string2Millis(it.startTime, format), format)
        val endTime = TimeUtils.millis2String(TimeUtils.string2Millis(it.endTime, format), format)
        mViewModel.startAndEndTime.set(getString(R.string.sign_time) + ":   $startTime  --  $endTime")

        if (dataImageList.isNotEmpty()) {
            mAdapter.setList(dataImageList)
            mAdapter.notifyDataSetChanged()
        }
        if (it.voucher.isEmpty()) {
            mDatabind.tvSubmitAppointmentProof.text = getString(R.string.Upload_credentials)
        } else {
            mDatabind.tvSubmitAppointmentProof.text = getString(R.string.Modify_credentials)
        }

        var btnContent = ""
        when (mState) {
            0 -> {
                btnContent = getString(R.string.commit_yuding)
                mDatabind.tvReserveState.text = getString(R.string.reserve_channel)
                mViewModel.isEdit.set(true)
                mDatabind.llOrderInfo.isVisible = false
                mDatabind.includeOrgTitle.llOrgInfo.isVisible = true
                mDatabind.ivReserveState.background = ContextCompat.getDrawable(this, R.mipmap.icon_under_review)
            }

            1 -> {
                btnContent = getString(R.string.Modify_reservation_information)
                mViewModel.isEdit.set(false)
                mDatabind.includeOrgTitle.llOrgInfo.isVisible = false
                mDatabind.llOrderInfo.isVisible = true
                mDatabind.tvReserveState.text = getString(R.string.have_already_booked)
                mDatabind.ivReserveState.background = ContextCompat.getDrawable(this, R.mipmap.icon_under_review)
            }

            3 -> {
                btnContent = getString(R.string.Resubmit_reservation)
                mViewModel.isEdit.set(true)
                mDatabind.includeOrgTitle.llOrgInfo.isVisible = false
                mDatabind.llOrderInfo.isVisible = true
                mDatabind.tvReserveState.text = getString(R.string.Failure_Audit)
                mDatabind.ivReserveState.background = ContextCompat.getDrawable(this, R.mipmap.icon_appointmenr_rejection)
            }

            else -> {
                mDatabind.llBottomBtn.isVisible = false
            }
        }
        mDatabind.tvSubmitAppointment.text = btnContent
        mDatabind.llRealNameInfo.isVisible = mIdCardState
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.tvMakeAnAppointmentArea,
            mDatabind.ivMakeAnAppointmentArea,
            mDatabind.tvSubmitAppointment,
            mDatabind.tvSubmitAppointmentProof,
            mDatabind.ivBack
        ) { it ->
            when (it) {
                mDatabind.ivBack -> {
                    finish()
                }

                mDatabind.tvSubmitAppointmentProof -> {
                    startActivityForResult<ActivitySubmitProof>("id" to mId, "activity" to "ActivityMakeAnAppointment") {
                        if (it != null && it.getBooleanExtra("isRefresh", false)) {
                            mViewModel.getMemberReservation(mRaceId.toString())
                        }
                    }
                }

                mDatabind.tvSubmitAppointment -> {
                    if (mState == 1) {
                        showModifyInfoDialog()
                    } else {
                        val memberName = mDatabind.etMakeAnAppointmentName.text.toString().trim()
                        val mobile = mDatabind.etMakeAnAppointmentMobile.text.toString().trim()
                        val raceArea = mDatabind.tvMakeAnAppointmentArea.text.toString().trim()
                        val realName = mDatabind.etMakeAnAppointmentRealName.text.toString().trim()
                        val iDCardNum = mDatabind.etMakeAnAppointmentNo.text.toString().trim()
                        val addressDetail = mDatabind.etMakeAnAppointmentAddressDetail.text.toString().trim()
                        submitAppointmentInfo(memberName, mobile, raceArea, addressDetail, iDCardNum, realName)
                    }
                }

                mDatabind.tvMakeAnAppointmentArea, mDatabind.ivMakeAnAppointmentArea -> {
                    startActivityForResult(ActivityAddress::class) {
                        if (it != null) {
                            provinceId = it.getIntExtra("provinceId", 0)
                            cityId = it.getIntExtra("cityId", 0)
                            areaId = it.getIntExtra("areaId", 0)
                            val addressResult = it.getStringExtra("addressResult")
                            mDatabind.tvMakeAnAppointmentArea.text = addressResult
                        }
                    }
                }
            }
        }
    }

    private fun showModifyInfoDialog() {
        val dialog = RxDialogModifyAppointmentInfo(this)
        dialog.setSureListener {
            submitAppointmentInfo(
                dialog.getMemberName(),
                dialog.getMobile(),
                dialog.geRaceArea(),
                dialog.getAddressDetail(),
                dialog.getIDCardNum(),
                dialog.getRealName()
            )
        }
        dialog.setChooseAddress {
            startActivityForResult(ActivityAddress::class) {
                if (it != null) {
                    provinceId = it.getIntExtra("provinceId", 0)
                    cityId = it.getIntExtra("cityId", 0)
                    areaId = it.getIntExtra("areaId", 0)
                    val addressResult = it.getStringExtra("addressResult").toString()
                    dialog.setAddressArea(addressResult)
                }
            }
        }
        dialog.setHideRealInfo(mIdCardState)
        if (::memberInfo.isInitialized) {
            dialog.setAppointmentInfo(memberInfo)
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun submitAppointmentInfo(
        memberName: String,
        mobile: String,
        raceArea: String,
        addressDetail: String,
        cardNo: String,
        realName: String,
    ) {

        if (memberName.isEmpty()) {
            RxToast.showToast(getString(R.string.enter_race_name))
            return
        }
        if (mobile.isEmpty()) {
            RxToast.showToast(getString(R.string.user_mobile_number))
            return
        }
        if (!Util.isTelPhoneNumber(mobile)) {
            RxToast.showToast(resources.getString(R.string.user_phone_number_wrong))
            return
        }
        if (raceArea.isEmpty()) {
            RxToast.showToast(getString(R.string.selective_race_area))
            return
        }
        if (mIdCardState) {
            if (realName.isEmpty()) {
                RxToast.showToast(getString(R.string.user_real_name))
                return
            }
            if (cardNo.isEmpty()) {
                RxToast.showToast(getString(R.string.user_id_number))
                return
            }
            if (!Util.isIdNO(this, cardNo)) {
                RxToast.showToast(resources.getString(R.string.user_id_number_wrong))
                return
            }
        }
        if (mState == 0) {
            val body = AddMemberReservationParam(
                raceId = mRaceId,
                name = memberName,
                detailAddr = addressDetail,
                mobile = mobile,
                realName = realName,
                IDCard = cardNo,
                num = 0,
                province = provinceId,
                city = cityId,
                region = areaId
            )
            showLoading(getString(R.string.loading))
            mViewModel.addMemberReservation(body)
        } else {
            val body = AddMemberReservationParam(
                id = mId,
                raceId = mRaceId,
                name = memberName,
                detailAddr = addressDetail,
                mobile = mobile,
                realName = realName,
                IDCard = cardNo,
                num = 0,
                province = provinceId,
                city = cityId,
                region = areaId
            )
            showLoading(getString(R.string.loading))
            mViewModel.editMemberReservation(body)
        }
    }

}